from flask import Flask, render_template, session, redirect, url_for, flash, jsonify
from flask import request
from flask import make_response
from flask_script import Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_script import Shell
from flask_migrate import Migrate, MigrateCommand
import os
import urllib.request
import urllib
import re,json
from urllib.error import URLError, HTTPError

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess str'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(basedir,'data.splite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)


@app.route('/ng')
def angtest():
    return render_template('ngbooks.html')

@app.route('/search/<name>',methods=['GET','POST'])
def search(name):
    url = "https://api.douban.com/v2/book/search?q=" + name

    try:
        data = urllib.request.urlopen(url).read()
        # print("douban------1-----" + str(data))
        data = data.decode('utf-8')
        # print("douban------2-----" + str(data))
        jsondata = json.loads(data)
        # print("douban------jsondata-----" + repr(jsondata))
        count = jsondata['count']
        print("douban------count----" + str(count))
        books = jsondata['books']
        # print("douban------books----" + books)
        # weatherJSON = json.JSONDecoder().decode(str(data))
        # print("json" + weatherJSON)
    except HTTPError as e:
        print("douban-----------" + str(e.code))
        print(e.reason)
        return ""

    return str(data)
    # return jsonify({'count':100})

if __name__ == '__main__':
    manager.run()
    # app.run(debug=True)